"""
后台管理模型
包含系统配置、操作日志、权限管理等功能
"""

from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone

User = get_user_model()


class SystemConfig(models.Model):
    """
    系统配置模型
    存储系统的各种配置参数
    """
    
    # 配置类型选择
    CONFIG_TYPE_CHOICES = [
        ('system', '系统配置'),
        ('business', '业务配置'),
        ('notification', '通知配置'),
        ('payment', '支付配置'),
        ('other', '其他配置'),
    ]
    
    key = models.CharField(
        max_length=100,
        unique=True,
        verbose_name='配置键'
    )
    
    value = models.TextField(
        verbose_name='配置值'
    )
    
    config_type = models.CharField(
        max_length=20,
        choices=CONFIG_TYPE_CHOICES,
        default='system',
        verbose_name='配置类型'
    )
    
    description = models.TextField(
        blank=True,
        verbose_name='配置描述'
    )
    
    is_active = models.BooleanField(
        default=True,
        verbose_name='是否启用'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间'
    )
    
    class Meta:
        verbose_name = '系统配置'
        verbose_name_plural = '系统配置'
        db_table = 'admin_system_configs'
        ordering = ['config_type', 'key']
    
    def __str__(self):
        return f"{self.key} ({self.get_config_type_display()})"


class OperationLog(models.Model):
    """
    操作日志模型
    记录管理员的操作行为
    """
    
    # 操作类型选择
    OPERATION_TYPE_CHOICES = [
        ('create', '创建'),
        ('update', '更新'),
        ('delete', '删除'),
        ('login', '登录'),
        ('logout', '登出'),
        ('export', '导出'),
        ('import', '导入'),
        ('other', '其他'),
    ]
    
    # 操作模块选择
    MODULE_CHOICES = [
        ('user', '用户管理'),
        ('circle', '校园圈子'),
        ('activity', '活动中心'),
        ('errand', '跑腿代办'),
        ('system', '系统管理'),
        ('other', '其他'),
    ]
    
    operator = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='operation_logs',
        verbose_name='操作者'
    )
    
    operation_type = models.CharField(
        max_length=20,
        choices=OPERATION_TYPE_CHOICES,
        verbose_name='操作类型'
    )
    
    module = models.CharField(
        max_length=20,
        choices=MODULE_CHOICES,
        verbose_name='操作模块'
    )
    
    description = models.CharField(
        max_length=200,
        verbose_name='操作描述'
    )
    
    detail = models.TextField(
        blank=True,
        verbose_name='操作详情'
    )
    
    ip_address = models.GenericIPAddressField(
        verbose_name='IP地址'
    )
    
    user_agent = models.TextField(
        blank=True,
        verbose_name='用户代理'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='操作时间'
    )
    
    class Meta:
        verbose_name = '操作日志'
        verbose_name_plural = '操作日志'
        db_table = 'admin_operation_logs'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.operator.username} - {self.description}"


class AdminPermission(models.Model):
    """
    管理员权限模型
    定义管理员的操作权限
    """
    
    name = models.CharField(
        max_length=100,
        unique=True,
        verbose_name='权限名称'
    )
    
    code = models.CharField(
        max_length=100,
        unique=True,
        verbose_name='权限代码'
    )
    
    description = models.TextField(
        blank=True,
        verbose_name='权限描述'
    )
    
    module = models.CharField(
        max_length=50,
        verbose_name='所属模块'
    )
    
    is_active = models.BooleanField(
        default=True,
        verbose_name='是否启用'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    
    class Meta:
        verbose_name = '管理员权限'
        verbose_name_plural = '管理员权限'
        db_table = 'admin_permissions'
        ordering = ['module', 'name']
    
    def __str__(self):
        return f"{self.name} ({self.module})"


class AdminRole(models.Model):
    """
    管理员角色模型
    定义管理员的角色
    """
    
    name = models.CharField(
        max_length=100,
        unique=True,
        verbose_name='角色名称'
    )
    
    description = models.TextField(
        blank=True,
        verbose_name='角色描述'
    )
    
    permissions = models.ManyToManyField(
        AdminPermission,
        related_name='roles',
        verbose_name='权限'
    )
    
    is_active = models.BooleanField(
        default=True,
        verbose_name='是否启用'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间'
    )
    
    class Meta:
        verbose_name = '管理员角色'
        verbose_name_plural = '管理员角色'
        db_table = 'admin_roles'
        ordering = ['name']
    
    def __str__(self):
        return self.name


class AdminUserRole(models.Model):
    """
    管理员用户角色关联模型
    关联管理员用户和角色
    """
    
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='admin_roles',
        verbose_name='用户'
    )
    
    role = models.ForeignKey(
        AdminRole,
        on_delete=models.CASCADE,
        related_name='users',
        verbose_name='角色'
    )
    
    assigned_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='assigned_roles',
        verbose_name='分配者'
    )
    
    assigned_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='分配时间'
    )
    
    is_active = models.BooleanField(
        default=True,
        verbose_name='是否启用'
    )
    
    class Meta:
        verbose_name = '管理员用户角色'
        verbose_name_plural = '管理员用户角色'
        db_table = 'admin_user_roles'
        unique_together = ['user', 'role']
        ordering = ['-assigned_at']
    
    def __str__(self):
        return f"{self.user.username} - {self.role.name}"


class Notification(models.Model):
    """
    通知模型
    存储系统通知信息
    """
    
    # 通知类型选择
    NOTIFICATION_TYPE_CHOICES = [
        ('system', '系统通知'),
        ('activity', '活动通知'),
        ('errand', '跑腿通知'),
        ('circle', '圈子通知'),
        ('other', '其他通知'),
    ]
    
    # 通知级别选择
    LEVEL_CHOICES = [
        ('info', '信息'),
        ('warning', '警告'),
        ('error', '错误'),
        ('success', '成功'),
    ]
    
    title = models.CharField(
        max_length=200,
        verbose_name='通知标题'
    )
    
    content = models.TextField(
        verbose_name='通知内容'
    )
    
    notification_type = models.CharField(
        max_length=20,
        choices=NOTIFICATION_TYPE_CHOICES,
        verbose_name='通知类型'
    )
    
    level = models.CharField(
        max_length=20,
        choices=LEVEL_CHOICES,
        default='info',
        verbose_name='通知级别'
    )
    
    # 接收者
    recipients = models.ManyToManyField(
        User,
        related_name='notifications',
        verbose_name='接收者'
    )
    
    # 发送者
    sender = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='sent_notifications',
        verbose_name='发送者'
    )
    
    # 通知设置
    is_broadcast = models.BooleanField(
        default=False,
        verbose_name='是否广播'
    )
    
    is_read = models.BooleanField(
        default=False,
        verbose_name='是否已读'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='发送时间'
    )
    
    class Meta:
        verbose_name = '通知'
        verbose_name_plural = '通知'
        db_table = 'admin_notifications'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.title} ({self.get_notification_type_display()})"


class DataStatistics(models.Model):
    """
    数据统计模型
    存储系统的统计数据
    """
    
    # 统计类型选择
    STAT_TYPE_CHOICES = [
        ('user', '用户统计'),
        ('circle', '圈子统计'),
        ('activity', '活动统计'),
        ('errand', '跑腿统计'),
        ('system', '系统统计'),
    ]
    
    stat_type = models.CharField(
        max_length=20,
        choices=STAT_TYPE_CHOICES,
        verbose_name='统计类型'
    )
    
    stat_date = models.DateField(
        verbose_name='统计日期'
    )
    
    stat_data = models.JSONField(
        verbose_name='统计数据'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    
    class Meta:
        verbose_name = '数据统计'
        verbose_name_plural = '数据统计'
        db_table = 'admin_data_statistics'
        unique_together = ['stat_type', 'stat_date']
        ordering = ['-stat_date']
    
    def __str__(self):
        return f"{self.get_stat_type_display()} - {self.stat_date}"
